<template>
	<div class="pagination">
		<button :disabled="currentPage <= 1" @click="setCurrentPage(currentPage - 1)">
			&lt; Previous
		</button>
		<button v-for="page in pages" :key="page" :class="{ active: currentPage === page }"
			@click="setCurrentPage(page)">
			{{ page }}
		</button>
		<button :disabled="currentPage >= totalPages" @click="setCurrentPage(currentPage + 1)">
			Next &gt;
		</button>
	</div>
</template>

<script lang="ts">
	import { defineComponent, PropType, ref, computed } from 'vue';

	export default defineComponent({
		name: 'Pagination',
		props: {
			totalItems: {
				type: Number as PropType<number>,
				required: true,
			},
			pageSize: {
				type: Number as PropType<number>,
				default: 10,
			},
		},
		emits: ['update:currentPage'],
		setup(props, { emit }) {
			const currentPage = ref(1);

			const totalPages = computed(() => Math.ceil(props.totalItems / props.pageSize));

			const pages = computed(() => {
				const range = [];
				for (let i = 1; i <= totalPages.value; i++) {
					range.push(i);
				}
				return range;
			});

			function setCurrentPage(page : number) {
				if (page < 1) page = 1;
				if (page > totalPages.value) page = totalPages.value;
				currentPage.value = page;
				emit('update:currentPage', page);
			}

			return { currentPage, totalPages, pages, setCurrentPage };
		},
	});
</script>

<style scoped>
	.pagination {
		display: flex;
		justify-content: center;
		list-style: none;
		padding: 0;
	}

	.pagination button {
		padding: 8px 12px;
		margin-right: 5px;
		border: 1px solid #ddd;
		background-color: #f8f8f8;
		cursor: pointer;
	}

	.pagination button.active {
		background-color: #007bff;
		color: white;
	}

	.pagination button:disabled {
		background-color: #ddd;
		cursor: not-allowed;
	}
</style>